import { mapState } from 'pinia'
import { find } from '@package/utils'
import { Http } from '@/common/api'
import { pinias } from '@/common/pinia'
import { EnumApiCode } from '../../../../../globalEnum.js'

const { cachedView } = pinias
const TableListMixin = {
  data() {
    return {
      /* 查询条件-请不要在queryParam中声明非字符串值的属性 */
      queryParam: {},
      // otherParam: {},
      /* 数据源 */
      tableData: [],
      /* 分页参数 */
      pagination: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      /* 排序参数 */
      sort: [],
      /* table加载状态 */
      loading: false,
      /* table选中keys */
      selectedRowKeys: [],
      /* table选中records */
      selectionRows: [],
      /* table的自定义列 */
      tableColumns: [],
      disableMixinCreated: false,
      creatFlag: false
    }
  },
  computed: {
    ...mapState(cachedView, ['visitedViews'])
  },
  created() {
    this.creatFlag = true
    if (!this.disableMixinCreated) {
      this.initDictConfig && this.initDictConfig() // 初始化字典配置 在自己页面定义
      if (this.listUrl && this.visitedViews) {
        this.loadData()
      }
    }
    this.tableColumns = this.columns
  },
  activated() {
    console.log('---activated--------')

    const temp = find(this.visitedViews, (view) => view.path === this.$route.path)
    if (!this.disableMixinCreated && this.creatFlag && !temp) {
      this.initDictConfig && this.initDictConfig() // 初始化字典配置 在自己页面定义
      if (this.listUrl) {
        this.resetSearch()
      }
    }
  },
  methods: {
    headClass() {
      return 'background:#EDEDED;'
    },
    // 选中背景色
    tableRowClassName({ row }) {
      return row.className
    },

    async loadData() {
      const params = {
        data: {
          ...this.queryParam,
          ...(this.otherParam || {})
        },
        ...this.pagination,
        sort: this.sort
      }
      this.loading = true
      // Http.post(this.listUrl,params).then(({data,code,msg}) =>{
      //   if (code === EnumApiCode.Success) {
      //     this.tableData = data?.list || []
      //     this.pagination.total = Number(data?.total || 0)
      //   }
      // },()=>{
      //   this.loading = false
      // })
      try {
        const { data, code } = await Http.post(this.listUrl, params)
        this.loading = false
        if (code === EnumApiCode.Success) {
          this.tableData = data?.list || []
          this.pagination.total = Number(data?.total || 0)
        }
      } finally {
        this.loading = false
      }
    },
    updateColumns(columns) {
      this.tableColumns = columns
      // this.$nextTick(() => {
      //   if (this.$refs.tableCom && this.$refs.tableCom.$refs.table.doLayout) {
      //     this.$refs.tableCom.$refs.table.doLayout()
      //   }
      // })
    },
    onClearSelected() {
      this.selectedRowKeys = []
      this.selectionRows = []
    },
    handleSearch(val) {
      this.queryParam = JSON.parse(JSON.stringify(val || this.searchParams || {}))
      this.pagination.pageNum = 1
      this.loadData()
    },
    resetSearch() {
      this.queryParam = {}
      this.searchParams = {}
      this.pagination.pageNum = 1
      this.loadData()
    },
    onSelectionChange(selection) {
      let resetSelection = selection
      if (selection.length > 0) {
        resetSelection = selection.map((item) => {
          return {
            ...item,
            className: 'selected-row-bg'
          }
        })
      }
      this.handleSelectionChange(resetSelection)
    },
    handleSelectionChange(selectionRows) {
      this.selectedRowKeys = selectionRows.map((item) => item.id)
      this.selectionRows = selectionRows
    },
    onSortChange(value) {
      this.handleTableChange(this.pagination, value)
    },
    handleTableChange(pagination, sorter, filters) {
      // 因onSortChange和onPageChange是同一个方法  导致页码改变后无法携带排序参数 添加此条件做判断
      if (sorter !== 'isPageChange') {
        if (sorter && sorter.order !== null) {
          this.sort = [
            {
              field: sorter.prop,
              type: sorter.order === 'ascending' ? 'asc' : 'desc'
            }
          ]
        } else {
          this.sort = []
        }
      }
      if (typeof filters !== 'undefined') {
        // 服务端筛选
      }
      this.pagination = pagination ? Object.assign(this.pagination, pagination) : this.pagination
      this.loadData().then()
    },
    async handleExport(exportUrl, isColumn = true, val) {
      const includeFieldNames = this.tableColumns.map((v) => v.prop)
      let param = {}
      if (isColumn) {
        param = {
          ...this.queryParam,
          ...(this.otherParam || {}),
          ...val,
          includeFieldNames // 指定导出的字段
          // excludeFieldNames:  // 不需要导出的字段
        }
      } else {
        param = val
      }
      try {
        const { code } = await Http.post(exportUrl, param)
        if (code === EnumApiCode.Success) {
          this.$message.success('正在导出,请去下载中心下载')
        }
      } finally {
        this.loading = false
      }
    }
  }
}
export default TableListMixin
